<template>
  <div>
    <!-- 选择广告计划的按钮和输入框 -->
    <div class="flex items-center">
      <el-input
        v-model="selectedName"
        :placeholder="placeholder"
        readonly
        class="mr-2"
        :disabled="disabled"
      />
      <el-button type="primary" :disabled="disabled" @click="openDialog"
        >选择{{ title }}</el-button
      >
    </div>

    <!-- 广告计划选择弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`选择${title}`"
      width="800px"
      destroy-on-close
      append-to-body
    >
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="mb-4">
        <el-form-item :prop="nameField">
          <el-input
            v-model="searchForm[nameField]"
            :placeholder="`搜索${title}名称`"
            clearable
            class="!w-[200px]"
          />
        </el-form-item>
        <el-form-item prop="adAccountId">
          <el-select
            v-model="searchForm.adAccountId"
            placeholder="选择广告账户"
            clearable
            filterable
            class="!w-[200px]"
          >
            <el-option
              v-for="item in adAccounts"
              :key="item.adAccountId"
              :label="item.adAccountName"
              :value="item.adAccountId"
              @change="handleSearchClick"
            />
          </el-select>
        </el-form-item>
        <!-- <el-form-item prop="timeZoneIana">
          <el-select
            v-model="searchForm.timeZoneIana"
            placeholder="选择时区"
            class="!w-[200px]"
            @change="handleSearchClick"
          >
            <el-option
              v-for="item in timeZoneOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[
              new Date(2000, 1, 1, 0, 0, 0),
              new Date(2000, 1, 1, 23, 59, 59)
            ]"
            @change="handleDateRangeChange"
          />
        </el-form-item> -->

        <el-form-item>
          <el-button
            type="primary"
            :icon="useRenderIcon('ri:search-line')"
            :loading="loading"
            @click="handleSearchClick"
          >
            搜索
          </el-button>
          <el-button :icon="useRenderIcon(Refresh)" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="dataList"
        height="400"
        border
        highlight-current-row
        @row-click="handleRowClick"
      >
        <el-table-column
          :prop="nameField"
          :label="`${title}名称`"
          min-width="250"
          show-overflow-tooltip
        />
        <el-table-column
          prop="campaignId"
          :label="`${title}ID`"
          min-width="150"
          show-overflow-tooltip
        />
        <el-table-column
          prop="adAccountId"
          label="广告账户ID"
          min-width="150"
          show-overflow-tooltip
        />
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelect">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, watch } from "vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import Refresh from "@iconify-icons/ep/refresh";
import { ElMessage } from "element-plus";
import { getUnitMapiList, getCampaignListMapi } from "@/api/promotion";
import dayjs from "dayjs";

// 定义类型
interface AdAccount {
  adAccountId: number;
  adAccountName: string;
}

const props = defineProps({
  title: {
    type: String,
    default: "广告计划"
  },
  placeholder: {
    type: String,
    default: "请选择广告计划"
  },
  type: {
    type: String,
    default: "campaign", // campaign 或 unit
    validator: (val: string) => ["campaign", "unit"].includes(val)
  },
  nameField: {
    type: String,
    default: "campaignName"
  },
  idField: {
    type: String,
    default: "campaignId"
  },
  adAccounts: {
    type: Array as () => AdAccount[],
    default: () => []
  },
  baseParams: {
    type: Object,
    default: () => ({
      timeZoneIana: "UTC+8",
      dataBeginTime: Date.now() - 7 * 24 * 60 * 60 * 1000, // 默认7天前
      dataEndTime: Date.now()
    })
  },
  valueId: {
    type: [String, Number],
    default: ""
  },
  valueName: {
    type: String,
    default: ""
  },
  disabled: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(["update:data", "update:valueName", "select"]);

// 弹窗相关
const dialogVisible = ref(false);
const selectedName = ref(props.valueName);
const loading = ref(false);
const dataList = ref([]);
const selectedItem = ref(null);

// 时区选项
const timeZoneOptions = [
  // { label: "UTC-5", value: "UTC-5" },
  // { label: "UTC-4", value: "UTC-4" },
  { label: "UTC-3", value: "UTC-3" },
  { label: "UTC+0", value: "UTC+0" },
  // { label: "UTC+1", value: "UTC+1" },
  // { label: "UTC+2", value: "UTC+2" },
  // { label: "UTC+3", value: "UTC+3" },
  // { label: "UTC+5", value: "UTC+5" },
  // { label: "UTC+6", value: "UTC+6" },
  // { label: "UTC+7", value: "UTC+7" },
  { label: "UTC+8", value: "UTC+8" }
];

// 日期范围
const dateRange = ref<[Date, Date]>([
  dayjs().subtract(7, "day").toDate(),
  dayjs().toDate()
]);

// 搜索表单
const searchForm = ref({
  [props.nameField]: "",
  adAccountId: props.adAccounts?.[0]?.adAccountId || "",
  timeZoneIana: "UTC+8",
  dataBeginTime: dayjs().subtract(7, "day").valueOf(),
  dataEndTime: dayjs().valueOf()
});

// 分页控制
const pagination = ref({
  total: 0,
  pageSize: 10,
  currentPage: 1
});

// 统一数据获取逻辑
const loadTableData = async () => {
  // 对于 MAPI 广告计划列表，adAccountId 至关重要。如果没有，则不获取数据。
  if (props.type === "campaign" && !searchForm.value.adAccountId) {
    dataList.value = [];
    pagination.value.total = 0;
    // ElMessage.warning("请选择一个广告账户以加载广告计划。"); // 可选：通知用户
    return;
  }
  // 对于广告组列表，adAccountId 可能也取决于 getUnitList 要求
  if (props.type === "unit" && !searchForm.value.adAccountId) {
    dataList.value = [];
    pagination.value.total = 0;
    // ElMessage.warning("请选择一个广告账户以加载广告组。"); // 可选
    return;
  }

  loading.value = true;
  try {
    let response;
    if (props.type === "campaign") {
      const campaignParams = {
        adAccountId: Number(searchForm.value.adAccountId),
        campaignName: searchForm.value[props.nameField] || undefined
      };
      response = await getCampaignListMapi(campaignParams);
      if (response && Array.isArray(response)) {
        dataList.value = response;
        pagination.value.total = response.length; // MAPI 列表通常没有服务器端分页总数
      } else if (response && response.data && Array.isArray(response.data)) {
        // 处理如果 MAPI 包装在 {data: []} 中
        dataList.value = response.data;
        pagination.value.total = response.data.length;
      } else {
        dataList.value = [];
        pagination.value.total = 0;
      }
    } else if (props.type === "unit") {
      const unitParams = {
        adAccountId: Number(searchForm.value.adAccountId),
        campaignIdList: [props.baseParams?.campaignId].join(","), // 确保将 campaignId 传递给 getUnitList
        unitName: searchForm.value[props.nameField] || undefined
        // page: pagination.value.currentPage,
        // size: pagination.value.pageSize,
        // timeZoneIana: searchForm.value.timeZoneIana, // getUnitList 可能需要这些
        // dataBeginTime: searchForm.value.dataBeginTime,
        // dataEndTime: searchForm.value.dataEndTime
      };
      response = await getUnitMapiList(unitParams);

      if (response) {
        // dataList.value = response.filter(item => {
        //   return item.campaignId == props.baseParams?.campaignId;
        // });
        dataList.value = response;
        pagination.value.total = 1;
      } else {
        dataList.value = [];
        pagination.value.total = 1;
      }
    }
  } catch (error) {
    console.error(`获取${props.title}列表失败:`, error);
    ElMessage.error(`获取${props.title}列表失败`);
    dataList.value = [];
    pagination.value.total = 0;
  } finally {
    loading.value = false;
  }
};

// 处理日期范围变化
const handleDateRangeChange = (dates: [Date, Date] | null) => {
  if (dates) {
    searchForm.value.dataBeginTime = dayjs(dates[0]).valueOf();
    searchForm.value.dataEndTime = dayjs(dates[1]).valueOf();
  } else {
    // 设置为默认值或清除，取决于所需的行为
    searchForm.value.dataBeginTime = dayjs(
      props.baseParams.dataBeginTime
    ).valueOf();
    searchForm.value.dataEndTime = dayjs(
      props.baseParams.dataEndTime
    ).valueOf();
  }
  handleSearchClick();
};

// 打开弹窗
const openDialog = () => {
  if (props.disabled) return;
  dialogVisible.value = true;
  // 对话框可见性监听器将处理初始化和数据获取
};

// 点击搜索按钮
const handleSearchClick = () => {
  pagination.value.currentPage = 1; // 重置到第一页以进行新搜索
  loadTableData();
};

const resetSearch = () => {
  searchForm.value = {
    [props.nameField]: "",
    adAccountId: props.adAccounts?.[0]?.adAccountId || "", // 重置到第一个广告账户或清除
    timeZoneIana: props.baseParams.timeZoneIana,
    dataBeginTime: props.baseParams.dataBeginTime,
    dataEndTime: props.baseParams.dataEndTime
  };
  dateRange.value = [
    dayjs(searchForm.value.dataBeginTime).toDate(),
    dayjs(searchForm.value.dataEndTime).toDate()
  ];
  pagination.value.currentPage = 1;
  loadTableData();
};

// 点击行
const handleRowClick = (row: any) => {
  selectedItem.value = row;
};

// 确认选择
const confirmSelect = () => {
  if (!selectedItem.value) {
    ElMessage.warning(`请选择一个${props.title}`);
    return;
  }
  selectedName.value = selectedItem.value[props.nameField];
  // 发出整个选定对象以获得灵活性，不仅仅是字符串化
  emit("update:data", selectedItem.value);
  emit("update:valueName", selectedItem.value[props.nameField]);
  emit("select", selectedItem.value);
  dialogVisible.value = false;
};

// 分页处理
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val;
  pagination.value.currentPage = 1; // 当大小变化时重置到页面1
  loadTableData();
};

const handleCurrentChange = (val: number) => {
  pagination.value.currentPage = val;
  loadTableData();
};

// 监听对话框可见性以初始化和获取数据
watch(
  () => dialogVisible.value,
  newVal => {
    if (newVal) {
      // 基于 props 初始化 searchForm
      searchForm.value = {
        [props.nameField]: "", // 清除名称搜索
        adAccountId:
          searchForm.value.adAccountId ||
          props.adAccounts?.[0]?.adAccountId ||
          "", // 优先现有，然后第一个 prop，然后空
        timeZoneIana: props.baseParams.timeZoneIana,
        dataBeginTime: props.baseParams.dataBeginTime,
        dataEndTime: props.baseParams.dataEndTime
      };
      // 更新日期范围选择器
      dateRange.value = [
        dayjs(searchForm.value.dataBeginTime).toDate(),
        dayjs(searchForm.value.dataEndTime).toDate()
      ];

      selectedItem.value = null; // 清除以前的选择
      pagination.value.currentPage = 1; // 重置到页面1

      loadTableData(); // 一次获取数据，一旦对话框打开并表单初始化
    }
  }
);

// 监听外部值Id以清除选择如果从外部重置
watch(
  () => props.valueId,
  newVal => {
    if (!newVal) {
      selectedName.value = "";
      selectedItem.value = null;
    } else {
      // 如果 valueId 是从外部设置的，并且我们有 dataList，尝试找到并设置项目
      // 这更复杂，可能需要获取特定项目如果不在当前列表中
      // 目前，只是确保本地状态如果外部ID被清除。
    }
  }
);

// 监听外部值名称以更新本地显示
watch(
  () => props.valueName,
  newVal => {
    selectedName.value = newVal;
  }
);

// 监听广告账户属性以更新搜索表单中默认广告账户如果最初为空
watch(
  () => props.adAccounts,
  newAdAccounts => {
    if (
      !searchForm.value.adAccountId &&
      newAdAccounts &&
      newAdAccounts.length > 0
    ) {
      searchForm.value.adAccountId = newAdAccounts[0].adAccountId;
      // 可选自动获取数据如果对话框已经可见，尽管对话框可见性监听器应该处理它。
      // if(dialogVisible.value) {
      //   loadTableData();
      // }
    }
  },
  { immediate: true }
);

// 监听 baseParams 以获取更改（例如，为单位选择器更改 campaignId）
watch(
  () => props.baseParams,
  (newParams, oldParams) => {
    let needsRefresh = false;
    if (newParams) {
      if (newParams.timeZoneIana !== searchForm.value.timeZoneIana) {
        searchForm.value.timeZoneIana = newParams.timeZoneIana;
        needsRefresh = true;
      }
      if (newParams.dataBeginTime !== searchForm.value.dataBeginTime) {
        searchForm.value.dataBeginTime = newParams.dataBeginTime;
        dateRange.value = [
          dayjs(newParams.dataBeginTime).toDate(),
          dayjs(searchForm.value.dataEndTime).toDate()
        ];
        needsRefresh = true;
      }
      if (newParams.dataEndTime !== searchForm.value.dataEndTime) {
        searchForm.value.dataEndTime = newParams.dataEndTime;
        dateRange.value = [
          dayjs(searchForm.value.dataBeginTime).toDate(),
          dayjs(newParams.dataEndTime).toDate()
        ];
        needsRefresh = true;
      }
      // 如果关键参数（如单位的选择）发生变化，也需要刷新
      if (
        props.type === "unit" &&
        newParams.campaignId !== oldParams?.campaignId
      ) {
        needsRefresh = true;
      }

      if (dialogVisible.value && needsRefresh) {
        pagination.value.currentPage = 1;
        loadTableData();
      }
    }
  },
  { deep: true } // 检查深对象更改
);
</script>
